package com.service.sso.sdk.interceptor;


import com.service.sso.sdk.config.SSOConfig;
import com.service.sso.sdk.dto.UserDto;
import com.service.sso.sdk.model.UserModel;
import com.service.sso.sdk.service.SsoService;
import com.service.sso.sdk.service.SsoUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private SsoUserService userService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private SSOConfig ssoConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserModel userModel = userService.getUser();
        if (null != userModel) {
            return true;
        }
        String token = request.getParameter("token");
        // 如果有token，需要去sso验证查询用户信息
        if (!StringUtils.isEmpty(token)) {
            UserDto userDto = ssoService.getUser(token);
            if (null != userDto) {
                userService.setUser(userDto);
                return true;
            }
        }

        String redirect = request.getRequestURL().toString();
        if (!StringUtils.isEmpty(redirect)) {
            redirect = URLEncoder.encode(redirect, "UTF-8");
        }
        response.sendRedirect(String.format("%s?oauth_callback=%s", ssoConfig.getLoginUrl(), redirect));
        return false;
    }
}
